package com.xiang.community.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.xiang.community.annotation.LoginRequired;
import com.xiang.community.dto.PageResult;
import com.xiang.community.dto.ResultDTO;
import com.xiang.community.entity.DiscussPost;
import com.xiang.community.entity.User;
import com.xiang.community.enums.DiscussPostStatusEnum;
import com.xiang.community.enums.DiscussPostTypeEnum;
import com.xiang.community.enums.ResponseCodeEnum;
import com.xiang.community.exceptions.BusinessException;
import com.xiang.community.service.CommonService;
import com.xiang.community.service.DiscussPostService;
import com.xiang.community.service.UserService;
import com.xiang.community.utils.CookieUtil;
import com.xiang.community.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.xiang.community.constant.LoginConstant.MAP_KEY_TOKEN;
import static com.xiang.community.constant.RedisUtilConstant.PREFIX_USER;
import static com.xiang.community.constant.RedisUtilConstant.PREFIX_USER_ID;

@Slf4j
@RestController
@RequestMapping("/home")
public class HomeController {

    @Resource
    private DiscussPostService discussPostService;
    @Resource
    private UserService userService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ObjectMapper mapper;
    @Resource
    private HttpServletRequest request;
    @Resource
    private CommonService commonService;

    /**
     * 排序条件：置顶、加精、热度、发布时间
     */
    private static final String ORDER_BY_CONDITON_ONE = "type desc, status desc";
    private static final String ORDER_BY_CONDITON_TWO = "create_time desc";

    /**
     * 分页查询帖子列表
     *
     * @param pageSize
     * @param pageNum
     * @return
     */
    @GetMapping("/postList")
    public PageResult getPostListWithPagePage(@RequestParam("pageSize") int pageSize, @RequestParam("pageNum") int pageNum,
                                              @RequestParam("orderBy") String orderBy) {
        if (orderBy == null || "newest".equals(orderBy)) {
            orderBy = ORDER_BY_CONDITON_ONE + "," + ORDER_BY_CONDITON_TWO;
        } else if ("hottest".equals(orderBy)) {
            orderBy = ORDER_BY_CONDITON_ONE + " ,score desc," + ORDER_BY_CONDITON_TWO;
        } else {
            throw new BusinessException(ResponseCodeEnum.CLIENT_ERROR.getCode(), "参数错误!");
        }

        PageInfo<DiscussPost> pageInfo = discussPostService.findDiscussPosts(pageNum, pageSize, null, orderBy);
        List<DiscussPost> discussPostList = pageInfo.getList();
        List<Map<String, Object>> discussPosts = new ArrayList<>(discussPostList.size());
        // 获取帖子发布人信息
        for (DiscussPost post : discussPostList) {
            Map<String, Object> map = new HashMap<>(8);
            map.put("post", post);
            User user = userService.findUserById(post.getUserId());
            map.put("user", user);
            discussPosts.add(map);
        }
        return PageResult.getInstance(pageInfo.getTotal(), discussPosts);
    }

    @PostMapping("/post")
    @LoginRequired
    public ResultDTO addPost(@RequestBody DiscussPost discussPost) {
        String currentUserId = redisUtil.getValueFromString(PREFIX_USER_ID, CookieUtil.getValue(request, MAP_KEY_TOKEN));
        User user = commonService.getUserByUserId(currentUserId);
        discussPost.setUserId(user.getId());
        discussPost.setCreateTime(new Date());
        discussPost.setScore(0L);
        discussPost.setType(DiscussPostTypeEnum.COMMON.getStatus());
        discussPost.setCommentCount(0);
        discussPost.setStatus(DiscussPostStatusEnum.COMMON.getStatus());
        return discussPostService.saveDiscussPost(discussPost);
    }

    @GetMapping("/myPostList")
    @LoginRequired
    public PageResult getPostListByUserIdWithPage(@RequestParam("pageSize") int pageSize, @RequestParam("pageNum") int pageNum,
                                                  @RequestParam("userId") Integer userId) throws JsonProcessingException {
        PageInfo<DiscussPost> pageInfo = discussPostService.findDiscussPosts(pageNum, pageSize, userId, null);
        List<DiscussPost> discussPostList = pageInfo.getList();
        List<Map<String, Object>> discussPosts = new ArrayList<>(discussPostList.size());
        // 获取帖子发布人信息
        User user = mapper.readValue(redisUtil.getValueFromString(PREFIX_USER, userId), User.class);
        for (DiscussPost post : discussPostList) {
            Map<String, Object> map = new HashMap<>(8);
            map.put("post", post);
            map.put("user", user);
            discussPosts.add(map);
        }
        return PageResult.getInstance(pageInfo.getTotal(), discussPosts);
    }

    @GetMapping("/search/{keyWord}")
    public PageResult searchDiscussPost(@PathVariable String keyWord, @RequestParam("pageSize") int pageSize,
                                        @RequestParam("pageNum") int pageNum) {
        return discussPostService.searchDiscussPost(keyWord, pageSize, pageNum);
    }
}
